package cn.com.inossem.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.foxykeep.datadroid.requestmanager.Request;
import com.netease.nim.uikit.common.util.log.LogUtil;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.SystemMessageService;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;

import cn.com.inossem.adapter.BottomTabTitleAdapter;
import cn.com.inossem.base.RequestActivity;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.fragment.PersonalCenterFragment;
import cn.com.inossem.operation.PackageVersionOperation;
import cn.com.inossem.requestmanager.WooRequestFactory;
import cn.com.inossem.utils.ActivityStackControlUtil;
import cn.com.inossem.utils.AsyncImageLoader;
import cn.com.inossem.utils.CrashHandlerUtil;
import cn.com.inossem.utils.DemoCache;
import cn.com.inossem.utils.Exit;
import cn.com.inossem.utils.PackageUtil;
import cn.com.inossem.utils.StringUtil;
import cn.com.inossem.utils.ToastUtil;
import cn.com.inossem.utils.Utils;
import cn.com.inossem.utils.view.FixedSpeedScroller;
import cn.com.inossem.utils.view.MyViewPager;
import cn.com.inossem.utils.wangyi.ReminderItem;
import cn.com.inossem.utils.wangyi.ReminderManager;
import cn.com.inossem.utils.wangyi.SystemMessageUnreadManager;
import cn.com.inossem.utils.wangyi.session.SessionHelper;
import cn.com.inossem.viewpagerindicator.IconPagerAdapter;
import cn.com.inossem.viewpagerindicator.TabPageIndicator;
import cn.jpush.android.api.JPushInterface;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

/**
 * ��ҳ�����
 * <p>
 * <p>
 * detailed comment
 *
 * @author szc 2015-8-24
 * @see
 * @since 1.0
 */
@RuntimePermissions
public class MainActivity extends RequestActivity implements
		ReminderManager.UnreadNumChangedCallback {
	public Context context = MainActivity.this;

	private MyViewPager mViewPager;

	private TabPageIndicator mPageIndicator;

	private int mImageViewArray[] = {R.drawable.tab_shouye,
			R.drawable.tab_ditu, R.drawable.tab_bagua, R.drawable.tab_wode};// tab_wode

	//	protected WooRequestManager mRequestManager = null;

	//	protected ArrayList<Request> mRequestList = null;

	//	protected boolean mContextDestroyed = false;

	//	private FragmentManager mFragmentManager;

	private FragmentTransaction mFragmentTransaction;

	private ProgressDialog progressDialog = null;

	public static int widthPixels, heightPixels;

	TextView tixing;

	public static boolean isForeground = false;

	private MessageReceiver mMessageReceiver;
	public static final String MESSAGE_RECEIVED_ACTION = "cn.com.inossem.activity.MESSAGE_RECEIVED_ACTION";
	public static final String KEY_MESSAGE = "str";
	protected static final String SAVED_STATE_REQUEST_LIST = "saved_state_request_list";
	private ProgressBar mProgress;
	private AlertDialog updateDialog;
	private File file;
	private Uri uri;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SessionHelper.init();

		JPushInterface.setDebugMode(true);
		JPushInterface.init(this);
		Utils.equipID = JPushInterface.getRegistrationID(this);

		DisplayMetrics DM = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(DM);
		widthPixels = DM.widthPixels;
		heightPixels = DM.heightPixels;

		registerMessageReceiver();

		SharedPreferences preferences = getSharedPreferences("index",
				MODE_PRIVATE);
		int index = preferences.getInt("index", 0);
		if (index == 0) {
			Editor editor = preferences.edit();
			editor.putInt("count", ++index);
			editor.commit();

			setInfo();
		}
		initView();
		launchRequest(WooRequestFactory.getPackageVersion());
		MainActivityPermissionsDispatcher.initCrashUtilWithCheck(this);
	}

	ProgressDialog pBar = null;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:
					mProgress.setProgress(progress);
					break;
				case 2:
					update();
					break;
				case 3:
					ToastUtil.show(MainActivity.this, "服务器连接失败！");
					break;
				default:
					break;
			}
		}

		;
	};
	private int progress;

	private void checkPackageVersion() {
		ContextThemeWrapper themedContext;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			themedContext = new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
		} else {
			themedContext = new ContextThemeWrapper(this, android.R.style.Theme_Light_NoTitleBar);
		}
		Builder builder = new AlertDialog.Builder(themedContext);
		builder.setMessage("检测到最新版本, 请及时更新!");
		builder.setTitle("版本升级");
		builder.setPositiveButton("更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				MainActivityPermissionsDispatcher.showDownloadDialogWithCheck(MainActivity.this);
			}
		});
		builder.setNegativeButton("暂不更新", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		builder.create().show();
	}

	@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
	public void initCrashUtil() {
		CrashHandlerUtil.getInstance().init(getApplicationContext());
	}

	@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
	public void showDownloadDialog() {
		ContextThemeWrapper themedContext;
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			themedContext = new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
		} else {
			themedContext = new ContextThemeWrapper(this, android.R.style.Theme_Light_NoTitleBar);
		}
		AlertDialog.Builder builder = new Builder(themedContext);
		builder.setTitle("软件版本更新");
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(R.layout.progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.progress);
		builder.setView(v);
		builder.setNegativeButton("取消", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		updateDialog = builder.create();
		updateDialog.show();
		//		downFile("http://123.57.137.89:8080/upload/Zhiren.apk");
		downFile(WSConfig.DOWNLOAD_APK + "/upload/Zhiren.apk");
	}

	void downFile(final String url) {
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				HttpResponse response;
				FileOutputStream fileOutputStream = null;
				try {
					response = client.execute(get);
					if (response.getStatusLine().getStatusCode() == 200) {
						HttpEntity entity = response.getEntity();
						long length = entity.getContentLength();
						InputStream is = entity.getContent();
						if (is != null) {
							//						File dir = new File(Environment.getExternalStorageDirectory(), "/zhiren");
							//						if (!dir.exists())
							//							dir.getParentFile().mkdirs();
							file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/zhiren/SapApp.apk");
							file.getParentFile().mkdirs();
							LogUtil.d("123", file.getPath());
							file.createNewFile();
							fileOutputStream = new FileOutputStream(file);
							byte[] buf = new byte[1024];
							int ch = -1;
							int count = 0;
							while ((ch = is.read(buf)) != -1) {
								fileOutputStream.write(buf, 0, ch);
								count += ch;
								progress = (int) (((float) count / length) * 100);
								//更新进度
								handler.sendEmptyMessage(1);
							}
							if (ch <= 0) {
								if (updateDialog != null)
									updateDialog.dismiss();
								//下载完成通知安装
								handler.sendEmptyMessage(2);
							}
						}
						fileOutputStream.flush();
					} else {
						if (updateDialog != null)
							updateDialog.dismiss();
						handler.sendEmptyMessage(3);
					}
				} catch (ClientProtocolException e) {
					LogUtil.d("Package", "" + e.getMessage());
				} catch (IOException e) {
					LogUtil.d("Package", "" + e.getMessage());
				} finally {
					if (fileOutputStream != null) {
						try {
							fileOutputStream.close();
						} catch (IOException e) {
							Log.i("Package", "" + e.getMessage());
						}
					}
				}
			}
		}.start();

	}

	void update() {
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
			uri = Uri.fromFile(file);
		} else {
			uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		}
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
		SharedPreferences preferences = context.getSharedPreferences("count", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		editor.putInt("count", 0);
		editor.commit();
	}

	public void registerMessageReceiver() {
		mMessageReceiver = new MessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		registerReceiver(mMessageReceiver, filter);
	}

	public class MessageReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			System.out.println("进了么");
			if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction()) && (Utils.isDenglu == 1)) {
				String str = intent.getStringExtra(KEY_MESSAGE);
				// String extras = intent.getStringExtra(KEY_EXTRAS);
				// StringBuilder showMsg = new StringBuilder();
				// showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
				// if (!ExampleUtil.isEmpty(extras)) {
				// showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
				// }
				// setCostomMsg(showMsg.toString());

				System.out.println("111111111111dasdsada11111111111:" + str);
				updatenNum(str, true);
			}
		}
	}

	public void updatenNum(String str, boolean isIncre) {
		if (Utils.messageInfo != null) {
			if (isIncre) {
				String messageNumStr = Utils.messageInfo.userInfo.getMessageNum();
				if (StringUtil.isNotBlank(messageNumStr)) {
					try {
						int messageNum = Integer.parseInt(messageNumStr);
						messageNum += 1;
						Utils.messageInfo.userInfo.setMessageNum(String.valueOf(messageNum));
					} catch (NumberFormatException e) {
						Log.i("Message", "Cann't format message number." + e);
					}
				}
			} else
				Utils.messageInfo.userInfo.setMessageNum(str);
		}
		int unreadNum = NIMClient.getService(MsgService.class)
				.getTotalUnreadCount();
		unreadNum += Integer.parseInt(str);
		tixing.setText(unreadNum + "");
		if (unreadNum == 0) {
			tixing.setVisibility(View.GONE);
		} else {
			tixing.setVisibility(View.VISIBLE);
		}
		if ((Utils.messageInfo != null) && (PersonalCenterFragment.center != null)) {
			PersonalCenterFragment.center.updateNum();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		JPushInterface.onResume(this);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		JPushInterface.onPause(this);
	}

	@Override
	public void onDestroy() {
		ActivityStackControlUtil.remove(this);
		// registerMsgUnreadInfoObserver(false);
		// registerSystemMessageObservers(false);
		registerMessageObservers(false);
		super.onDestroy();
	}

	private void initView() {
		// String location = Utils.getLocation(context); // ��ȡ����������Ϣ
		// System.out.println(location + "////////////////////////");

		ActivityStackControlUtil.add(this);

		try {
			CreateText();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		mViewPager = (MyViewPager) findViewById(R.id.view_pager);
		mPageIndicator = (TabPageIndicator) findViewById(R.id.indicator);

		tixing = (TextView) this.findViewById(R.id.tixing);
		try {
			Field mScroller;
			mScroller = ViewPager.class.getDeclaredField("mScroller");
			mScroller.setAccessible(true);
			Interpolator sInterpolator = new AccelerateDecelerateInterpolator();
			FixedSpeedScroller scroller = new FixedSpeedScroller(
					mViewPager.getContext(), sInterpolator);
			mScroller.set(mViewPager, scroller);
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int index) {
				// mTitleTextView.setText(getAdapter().getPageTitle(index));
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		HomePageAdapterPhone mHomePageAdapter = new HomePageAdapterPhone(this,
				getSupportFragmentManager());
		mViewPager.setAdapter(mHomePageAdapter);// setOffscreenPageLimit
		mViewPager.setOffscreenPageLimit(0);
		mPageIndicator.setViewPager(mViewPager, 0);
	}

	public void setPageView(int page) {
		// mPageIndicator.setViewPager(mViewPager, page);

		mPageIndicator.selectPage(page);
	}

	class HomePageAdapterPhone extends BottomTabTitleAdapter implements
			IconPagerAdapter {

		public HomePageAdapterPhone(Context context, FragmentManager fm) {
			super(context, fm);
		}

		@Override
		public int getIconResId(int index) {
			return mImageViewArray[index % mImageViewArray.length];
		}

		// @Override
		// public int getCount()
		// {
		// return 0;
		// }
	}

	Exit exit = new Exit();

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {

			pressAgainExit();

			return true;

		}

		return super.onKeyDown(keyCode, event);

	}

	private void pressAgainExit() {

		if (exit.isExit()) {
			ActivityStackControlUtil.exitApp();
			// finish();

		} else {

			Toast.makeText(getApplicationContext(), "在按一次退出！", Toast.LENGTH_LONG).show();

			exit.doExitInOneSecond();

		}
	}

	/*@Override
	public void initAllMembers(Bundle savedInstanceState) {
		mContextDestroyed = false;
		mRequestManager = WooRequestManager.from(this);
		mFragmentManager = getSupportFragmentManager();
		if (savedInstanceState != null) {
			mRequestList = savedInstanceState
					.getParcelableArrayList(SAVED_STATE_REQUEST_LIST);
		}
		if (mRequestList == null) {
			mRequestList = new ArrayList<Request>();
		}

	}*/

	@Override
	public Request getInitialRequest() {
		return null;

	}

	@Override
	public void onRequestSucess(Request request, Bundle bundle) {
		if (bundle.containsKey(PackageVersionOperation.PACKAGE_VERSION_OPERATION_STR)) {
			String version = bundle.getString(PackageVersionOperation.PACKAGE_VERSION_OPERATION_STR);
			String nowVersion = PackageUtil.getVersionName(context);
			if (PackageUtil.compareVersion(version, nowVersion) > 0) {
				checkPackageVersion();
			}
		}
	}

	@Override
	public void onRequestError(int exceptionType) {

	}

	public int getContentViewId() {
		return R.layout.main_tab_layout;

	}

	public void guanbijianpan() {
		if (getCurrentFocus() != null) {
			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(
							getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);
		}
	}

	private void setInfo() {
		// 获得SharedPreferences对象
		SharedPreferences settings = this.getSharedPreferences("shared_file",
				Activity.MODE_PRIVATE);

		// 获得可编辑对象
		SharedPreferences.Editor editor = settings.edit();
		int random = (int) (Math.random() * Utils.niming.length);
		editor.putString("name", Utils.niming[random]);
		int picrandom = 1 + (int) (Math.random() * 16);
		editor.putString("picname", "h" + picrandom);
		editor.commit();
	}

	private void getInfo() {
		SharedPreferences settings = this
				.getSharedPreferences("shared_file", 0);

		int random = (int) (Math.random() * Utils.niming.length);
		String name = settings.getString("name", Utils.niming[random]);
		int picrandom = 1 + (int) (Math.random() * 16);
		String picname = settings.getString("picname", "h" + picrandom);
		boolean ishuaming = settings.getBoolean("ishuaming", true);
	}

	public void doLogin() {
		LoginInfo info = new LoginInfo(Utils.messageInfo.userInfo.getId() + "",
				"db9f13b7b21953594524248188554e16"); // config...
		RequestCallback<LoginInfo> callback = new RequestCallback<LoginInfo>() {

			@Override
			public void onException(Throwable arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailed(int arg0) {
				// TODO Auto-generated method stub
				System.out.println("arg0:" + arg0);
			}

			@Override
			public void onSuccess(LoginInfo arg0) {
				// TODO Auto-generated method stub
				// 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
				DemoCache.setAccount(Utils.messageInfo.userInfo.getId() + "");
				System.out.println("登入成功！！！！！！！！！！！！！！！！！！！！！！");

				startNum();
				// int num = requestSystemMessageUnreadCount();
				int unreadNum = NIMClient.getService(MsgService.class)
						.getTotalUnreadCount();
				int num = unreadNum
						+ Integer.parseInt(Utils.messageInfo.userInfo
						.getMessageNum());
				tixing.setText(num + "");
				if (num == 0) {
					tixing.setVisibility(View.GONE);
				} else {
					tixing.setVisibility(View.VISIBLE);
				}

				List<String> accounts = NIMClient.getService(
						FriendService.class).getFriendAccounts(); // 获取所有好友帐号

				System.out.println("accounts::::::" + accounts.size());
				NIMClient.getService(UserService.class).fetchUserInfo(accounts)
						.setCallback(new RequestCallback<List<NimUserInfo>>() {

							@Override
							public void onException(Throwable arg0) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onFailed(int arg0) {
								// TODO Auto-generated method stub

							}

							@Override
							public void onSuccess(List<NimUserInfo> arg0) {
								// TODO Auto-generated method stub

							}
						});
			}

		};
		NIMClient.getService(AuthService.class).login(info)
				.setCallback(callback);
	}

	public void startNum() {
		// registerMsgUnreadInfoObserver(true);
		// registerSystemMessageObservers(true);
		registerMessageObservers(true);
	}

	// 创建观察者对象
	Observer<List<RecentContact>> messageObserver = new Observer<List<RecentContact>>() {
		@Override
		public void onEvent(List<RecentContact> messages) {
			int unreadNum = NIMClient.getService(MsgService.class)
					.getTotalUnreadCount();
			tixing.setText(unreadNum + "");
			if (unreadNum == 0) {
				tixing.setVisibility(View.GONE);
			} else {
				tixing.setVisibility(View.VISIBLE);
			}

			if (PersonalCenterFragment.center != null) {
				if (PersonalCenterFragment.center.num != null) {
					PersonalCenterFragment.center.num.setText(unreadNum + "");
					if (unreadNum == 0) {
						PersonalCenterFragment.center.num
								.setVisibility(View.GONE);
					} else {
						PersonalCenterFragment.center.num
								.setVisibility(View.VISIBLE);
					}

				}
			}
		}
	};

	private void registerMessageObservers(boolean register) {
		// 注册/注销观察者
		NIMClient.getService(MsgServiceObserve.class).observeRecentContact(
				messageObserver, register);
	}

	/**
	 * 注册/注销系统消息未读数变化
	 *
	 * @param register
	 */
	private void registerSystemMessageObservers(boolean register) {
		NIMClient.getService(SystemMessageObserver.class)
				.observeUnreadCountChange(sysMsgUnreadCountChangedObserver,
						register);
	}

	private Observer<Integer> sysMsgUnreadCountChangedObserver = new Observer<Integer>() {
		@Override
		public void onEvent(Integer unreadCount) {
			SystemMessageUnreadManager.getInstance().setSysMsgUnreadCount(
					unreadCount);
			ReminderManager.getInstance().updateContactUnreadNum(unreadCount);

			System.out.println("unreadCount:" + unreadCount);

			int num = unreadCount
					+ Integer.parseInt(Utils.messageInfo.userInfo
					.getMessageNum());
			tixing.setText(num + "");
			if (num == 0) {
				tixing.setVisibility(View.GONE);
			} else {
				tixing.setVisibility(View.VISIBLE);
			}
		}
	};

	@Override
	public void onUnreadNumChanged(ReminderItem item) {
		// TODO Auto-generated method stub

	}

	/**
	 * 注册未读消息数量观察者
	 */
	private void registerMsgUnreadInfoObserver(boolean register) {
		if (register) {
			ReminderManager.getInstance()
					.registerUnreadNumChangedCallback(this);
		} else {
			ReminderManager.getInstance().unregisterUnreadNumChangedCallback(
					this);
		}
	}

	/**
	 * 查询系统消息未读数
	 */
	private int requestSystemMessageUnreadCount() {
		int unread = NIMClient.getService(SystemMessageService.class)
				.querySystemMessageUnreadCountBlock();
		SystemMessageUnreadManager.getInstance().setSysMsgUnreadCount(unread);
		ReminderManager.getInstance().updateContactUnreadNum(unread);
		System.out.println("unread:" + unread);
		System.out.println("unread:" + unread);
		System.out.println("unread:" + unread);
		System.out.println("unread:" + unread);

		return unread;
	}

	String filenameTemp = AsyncImageLoader.imgpath;

	// 创建文件夹及文件
	public void CreateText() throws IOException {
		File file = new File(filenameTemp + ".nomedia");
		if (!file.exists()) {
			try {
				// 按照指定的路径创建文件夹
				file.mkdirs();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		// File dir = new File(filenameTemp + ".nomedia");
		// if (!dir.exists()) {
		// try {
		// // 在指定的文件夹中创建文件
		// dir.createNewFi4le();
		// } catch (Exception e) {
		// }
		// }
		//
	}
}
